import request from 'common/js/token/request'  //添加修改等 需要登录
import axios from 'axios'   //  查询评论  不需要登录

/**
 * 获取评论列表
 * @param   sku pageSize  pageNumber
 * https://testapi.meet50off.com/api/Review/list?SKU=B01N8THDCN&IsVerified=true&PageNumber=1&PageSize=11
 */

export function getAllReviews(data) {
  let url = '/api/Review/list'
  url += (url.indexOf('?') < 0 ? '?' : '&') + param(data)

  return axios.get(url)
    .then(res => {
      return Promise.resolve(res.data)
    })
    .catch(err => {
      console.log(err)
    })
}

export function postReview({rating, content, sku, parentSKU}) {
  const url = '/api/Review'
  const data = {
    rating,
    content,
    sku,
    parentSKU
  }
  return request.post(url, data)
    .then(response => {
      return Promise.resolve(response.data)
    })
    .catch(error => {
      console.log(error)
    })
}

export function deleteReview(reviewId) {
  const url = `/api/Review/${reviewId}`
  return request.delete(url)
    .then(response => {
      return Promise.resolve(response.data)
    })
    .catch(error => {
      console.log(error)
    })
}

export function postHelpful(reviewId) {
  const url = `/api/Review/${reviewId}/helpful`
  return request.post(url)
    .then(response => {
      return Promise.resolve(response.data)
    })
    .catch(error => {
      console.log(error)
    })
}

export function delHelpful(reviewId) {
  const url = `/api/Review/${reviewId}/helpful`
  return request.delete(url)
    .then(response => {
      return Promise.resolve(response.data)
    })
    .catch(error => {
      console.log(error)
    })
}

function param(data) {
  let url = ''
  for (var k in data) {
    let value = data[k] !== undefined ? data[k] : ''
    url += `&${k}=${encodeURIComponent(value)}`
  }
  return url ? url.substring(1) : ''
}
